package trss.webapp.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

import org.apache.myfaces.custom.fileupload.UploadedFile;

import trss.bencode.BFormatException;
import trss.model.Torrent;
import trss.model.User;
import trss.service.TorrentManager;

public class TorrentFileUpload extends BasePage implements Serializable {
    private static final long serialVersionUID = 408805132977668150L;
    private UploadedFile file;
    private TorrentManager torrentManager;

    /**
     * @return the torrentManager
     */
    public TorrentManager getTorrentManager() {
        return torrentManager;
    }

    /**
     * @param torrentManager the torrentManager to set
     */
    public void setTorrentManager(TorrentManager torrentManager) {
        this.torrentManager = torrentManager;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public String upload() throws IOException {
        HttpServletRequest request = getRequest();

        //retrieve the file data
        InputStream stream = file.getInputStream();
        String filename = file.getName();

        // APF-946: Canoo Web Tests R_1702 sets full path as name instead of only file name
        if (filename.indexOf("/") > -1) {
            filename = filename.substring(filename.lastIndexOf("/") + 1);
        }

        // APF-758: Fix for Internet Explorer's shortcomings
        if (filename.indexOf("\\") != -1) {
            int slash = filename.lastIndexOf("\\");
            if (slash != -1) {
                filename = filename.substring(slash + 1);
            }
            // Windows doesn't like /'s either
            int slash2 = filename.lastIndexOf("/");
            if (slash2 != -1) {
                filename = filename.substring(slash2 + 1);
            }
            // In case the name is C:foo.txt
            int slash3 = filename.lastIndexOf(":");
            if (slash3 != -1) {
                filename = filename.substring(slash3 + 1);
            }
        }
        
        try {
            Torrent torrent = new Torrent(filename, stream);
            User user = getCurrentUser();
            torrent.setOwner(user);
            torrentManager.save(torrent);
        } catch (BFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //close the stream
        stream.close();
        request.setAttribute("fileName", filename);
        request.setAttribute("contentType", file.getContentType());
        request.setAttribute("size", file.getSize() + " bytes");
        
        return "success";
    }

	private User getCurrentUser() {
		String username = getFacesContext().getExternalContext().getRemoteUser();
		User user = userManager.getUserByUsername(username);
		return user;
	}
}
